package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.message.FollowBehaviorConstants;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @作者 itcast
 * @创建日期 2020/10/7 15:43
 **/
@Service
@Slf4j
@Transactional
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    private ArticleFeign articleFeign;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        // 参数校验
        if (dto == null || (dto.getOperation() != 0 && dto.getOperation() != 1)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "作者信息不能为空");
        }
        // 获取作者信息
        Integer followId = null; // 要关注的用户ID
        ApAuthor author = articleFeign.findById(dto.getAuthorId());
        if (author != null) {
            followId = author.getUserId();
        }
        if (followId == null) {
            // 要关注的人信息不存在
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 获取当前登录用户ID
        ApUser user = AppThreadLocalUtils.getUser();
        if (user != null) {
            // 判断是 关注还是取关 分别做不同的处理
            if (dto.getOperation() == 0) {
                //3.如果当前操作是0 创建数据（app用户关注信息和app的用户粉丝信息）
                return followByUserId(user, followId, dto.getArticleId());
            } else {
                //4.如果当前操作是1 删除数据（app用户关注信息和app的用户粉丝信息）
                return followCancelByUserId(user, followId, dto.getArticleId());
            }
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
    }

    @Autowired
    ApUserMapper apUserMapper;
    @Autowired
    ApUserFollowMapper apUserFollowMapper;
    @Autowired
    ApUserFanMapper apUserFanMapper;
    @Autowired
    KafkaTemplate kafkaTemplate;

    /**
     * 关注
     * @param apUser    当前登录人
     * @param followId  要关注人 apuser ID
     * @param articleId 文章ID
     * @return
     */
    private ResponseResult followByUserId(ApUser apUser, Integer followId, Long articleId) {
        // 判断要关注的人是否存在
        ApUser followUser = apUserMapper.selectById(followId);
        if (followUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "关注人不存在");
        }
        // 查看是否已经关注过
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(
                Wrappers.<ApUserFollow>lambdaQuery()
                        .eq(ApUserFollow::getUserId, apUser.getId())
                        .eq(ApUserFollow::getFollowId, followId));
        // 如果没关注过， 保存关注信息 保存粉丝信息
        if (apUserFollow == null) {
            // 保存app粉丝信息
            ApUserFan apUserFan = apUserFanMapper.selectOne(
                    Wrappers.<ApUserFan>lambdaQuery()
                            .eq(ApUserFan::getUserId, followId)
                            .eq(ApUserFan::getFansId, apUser.getId()));
            if(apUserFan == null){
                apUserFan = new ApUserFan();
                apUserFan.setUserId(followId);
                apUserFan.setFansId(apUser.getId().longValue());
                apUserFan.setLevel((short)0);
                apUserFan.setCreatedTime(new Date());
                apUserFan.setIsDisplay(true);
                apUserFan.setIsShieldComment(false);
                apUserFan.setIsShieldLetter(false);
                apUserFanMapper.insert(apUserFan);
            }
            // 保存app关注信息
            apUserFollow = new ApUserFollow();
            apUserFollow.setUserId(apUser.getId());
            apUserFollow.setCreatedTime(new Date());
            apUserFollow.setFollowId(followId);
            apUserFollow.setFollowName(followUser.getName());
            apUserFollow.setIsNotice(true);
            apUserFollow.setLevel((short)1);
            apUserFollowMapper.insert(apUserFollow);
            // 发送消息 保存关注行为
            FollowBehaviorDto dto = new FollowBehaviorDto();
            dto.setFollowId(followId);
            dto.setArticleId(articleId);
            dto.setUserId(apUser.getId());
            kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(dto));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "已经关注");
        }
    }
    /**
     * 取关
     * @param apUser    当前登录人
     * @param followId  要取关人  apuser ID
     * @param articleId 文章ID
     * @return
     */
    private ResponseResult followCancelByUserId(ApUser apUser, Integer followId, Long articleId) {
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(
                Wrappers.<ApUserFollow>lambdaQuery()
                        .eq(ApUserFollow::getUserId, apUser.getId())
                        .eq(ApUserFollow::getFollowId, followId));
        if(apUserFollow == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"未关注");
        }else {
            ApUserFan apUserFan = apUserFanMapper.selectOne(
                    Wrappers.<ApUserFan>lambdaQuery()
                            .eq(ApUserFan::getUserId, followId)
                            .eq(ApUserFan::getUserId, apUser.getId()));
            // 删除粉丝表信息
            if(apUserFan!=null){
                apUserFanMapper.delete(
                        Wrappers.<ApUserFan>lambdaQuery()
                        .eq(ApUserFan::getUserId, followId)
                        .eq(ApUserFan::getUserId, apUser.getId()));
            }
            // 删除关注表信息
            apUserFollowMapper.delete(
                    Wrappers.<ApUserFollow>lambdaQuery()
                    .eq(ApUserFollow::getUserId, apUser.getId())
                    .eq(ApUserFollow::getFollowId, followId));
            return ResponseResult.okResult();
        }
    }
}
